'''

Case Type： 套接字文件
Case Name： 套接字文件丢失后停止数据库
Create At:  2020/06/28
Owner    :  n@ningyali
Descption:  1.从配置文件中获取套接字文件路径 2.获取套接字文件名 3.删除套接字文件 4.停止数据库 5.还原

'''

import os
import sys
import unittest
import time
from yat.test import Node

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import *


class SocketFileLostStopDb(unittest.TestCase):
    sh = CommonSH()
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case083.py start------------')
        self.dbUserNode = Node(node='dbuser')

    def test_socket_lost_stop_db(self):
        self.log.info('----------------------------test1:套接字文件丢失后停止数据库-----------------------------')
        try:
            # 获取套接字文件路径
            get_socket_dir_cmd = f"show unix_socket_directory;"
            self.log.info(get_socket_dir_cmd)
            msg = self.sh.executDbSql(get_socket_dir_cmd)
            self.log.info(msg)
            msg = msg.splitlines()
            socket_dir = msg[-2].strip()
            self.log.info(socket_dir)

            # 获取套接字文件名
            get_file_list_cmd = f'ls -a {socket_dir}'
            self.log.info(get_file_list_cmd)
            file_list = self.dbUserNode.sh(get_file_list_cmd).result()
            self.log.info(file_list)
            socket_file_name = ''
            for file in file_list.split():
                self.log.info(file)
                if (self.dbUserNode.db_port not in file) or ('lock' in file):
                    pass
                else:
                    socket_file_name = file

            # 删除套接字文件
            self.log.info(socket_dir)
            self.log.info(socket_file_name)
            socket_file_path = os.path.join(socket_dir, socket_file_name)
            del_cmd = f'rm -rf {socket_file_path}'
            self.log.info(del_cmd)
            del_msg = self.dbUserNode.sh(del_cmd).result()
            self.log.info(del_msg)
            self.assertEqual(del_msg, '')

            # 停止数据库
            is_stoped = self.sh.stopDbCluster()
            self.assertTrue(is_stoped)

            time.sleep(3)
        finally:
            # 还原套接字文件（重启或修改配置参数可自动生成，此处选重启）
            is_started = self.sh.startDbCluster()
            self.assertTrue(is_started)

    def tearDown(self):
        self.log.info('--------------Opengauss_Reliability_Dbsys_Case083 end----------------')
